package com.flux.service;

import com.flux.dao.UserDao;
import com.flux.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.persistence.EntityNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created by acer on 2018/4/8.
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User save(User user) {
        return userDao.save(user);
    }

    public void remove(Integer id) {
        userDao.deleteById(id);
    }

    public User find(Integer id) {
        Optional<User> userOp = userDao.findById(id);
        return userOp.orElse(null);
    }

    public List<User> findAll() {
        return userDao.findAll();
    }
/////////////////下边是Flux方式

    public Flux<User> list() {
        return Flux.fromIterable(findAll());
    }

    public Flux<User> getById(Flux<Integer> ids) {
        return ids.flatMap(id -> Mono.justOrEmpty(find(id)));
    }

    public Mono<User> getById(Integer id) {
        return Mono.justOrEmpty(find(id)).switchIfEmpty(
                Mono.error(new EntityNotFoundException(String.format("找不到id为%s的对象", id))));
    }

    public Flux<User> createOrUpdate(Flux<User> users) {
        return users.doOnNext(user -> save(user));
    }

    public Mono<User> createOrUpdate(User user) {
        return Mono.just(save(user));
    }

    public Mono<User> delete(Integer id) {
        User user = find(id);
        if (null != user) {
            userDao.delete(user);
            return Mono.just(user);
        }
        return Mono.error(new EntityNotFoundException(String.format("找不到id为%s的对象", id)));
    }
}